Page({

  /**
   * 页面的初始数据
   */
  data: {
    habit_category: [],
    habits: {},
    loading: true, // 加载状态
    error: null // 错误信息
  },

  goAdd: function (e) {
    var id = e.target.id;
    wx.navigateTo({
      url: '../../pages/habit_content/habit_content?id=' + id
    });
  },
  goAdd0: function () {
    var id = 0; //id=0标记该id需要重新分配
    wx.navigateTo({
      url: '../../pages/habit_content/habit_content?id=' + id
    });
  },
  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function () {
    //习惯库渲染
    this.fetchData();
  },
  fetchData: function () {
    wx.request({
      url: 'http://127.0.0.1:3001/data',
      method: 'GET',
      success: (res) => {
        const categories = res.data;
        this.setData({
          habit_category: categories
        });
        if (categories && categories.length > 0) {
          const promises = categories.map(category => {
            return new Promise((resolve, reject) => {
              wx.request({
                url: `http://127.0.0.1:3001/habitData?habit_category_id=${category.habit_category_id}`,
                method: 'GET',
                success: (habitRes) => {
                  resolve({
                    categoryId: category.habit_category_id,
                    habits: habitRes.data
                  });
                },
                fail: (err) => {
                  console.error(`获取类别 ${category.habit_category_id} 的习惯数据失败:`, err);
                  reject(err);
                }
              });
            });
          });
          // 等待所有请求完成后更新数据
          Promise.all(promises).then(results => {
            const habitsMap = {};
            results.forEach(result => {
              habitsMap[result.categoryId] = result.habits;
            });

            this.setData({
              habits: habitsMap
            });
          }).catch(err => {
            console.error('加载习惯数据出错:', err);
          });
        }
      },
      fail: (err) => {
        console.error('获取分类数据失败:', err);
      }
    });
  },
  goToDetail(e) {
    const { habit_id, user_id } = e.currentTarget.dataset;
    wx.navigateTo({
      url: `/pages/stat_detail/stat_detail?habit_id=${habit_id}&user_id=${user_id}`
    });
  },
});